import React, { useState, useEffect } from 'react';

interface ThemeToggleProps {
  currentTheme: 'light' | 'dark' | 'system';
  onThemeChange: (theme: 'light' | 'dark' | 'system') => void;
}

const ThemeToggle: React.FC<ThemeToggleProps> = ({ currentTheme, onThemeChange }) => {
  const [isOpen, setIsOpen] = useState(false);

  // Apply theme to document
  useEffect(() => {
    const applyTheme = (theme: 'light' | 'dark' | 'system') => {
      const root = document.documentElement;
      
      if (theme === 'system') {
        const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
        root.classList.toggle('dark', prefersDark);
      } else {
        root.classList.toggle('dark', theme === 'dark');
      }
    };

    applyTheme(currentTheme);

    // Listen for system theme changes when in system mode
    if (currentTheme === 'system') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      const handleChange = () => applyTheme('system');
      
      mediaQuery.addEventListener('change', handleChange);
      return () => mediaQuery.removeEventListener('change', handleChange);
    }
  }, [currentTheme]);

  const themes = [
    { 
      id: 'light', 
      label: 'Light', 
      icon: '☀️',
      description: 'Light appearance'
    },
    { 
      id: 'dark', 
      label: 'Dark', 
      icon: '🌙',
      description: 'Dark appearance'
    },
    { 
      id: 'system', 
      label: 'System', 
      icon: '💻',
      description: 'Match system setting'
    }
  ] as const;

  const currentThemeConfig = themes.find(theme => theme.id === currentTheme);

  const handleThemeChange = (themeId: 'light' | 'dark' | 'system') => {
    onThemeChange(themeId);
    setIsOpen(false);
  };

  return (
    <div className="relative">
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center space-x-2 px-3 py-2 bg-ios-gray-100 dark:bg-ios-gray-700 hover:bg-ios-gray-200 dark:hover:bg-ios-gray-600 rounded-apple-md transition-colors"
        title="Toggle theme"
      >
        <span className="text-lg">{currentThemeConfig?.icon}</span>
        <span className="hidden sm:inline text-sm font-medium text-ios-gray-700 dark:text-ios-gray-300">
          {currentThemeConfig?.label}
        </span>
        <svg 
          className={`w-4 h-4 text-ios-gray-500 dark:text-ios-gray-400 transition-transform ${isOpen ? 'rotate-180' : ''}`}
          fill="none" 
          stroke="currentColor" 
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {isOpen && (
        <>
          {/* Backdrop */}
          <div 
            className="fixed inset-0 z-10" 
            onClick={() => setIsOpen(false)}
          />
          
          {/* Dropdown Menu */}
          <div className="absolute right-0 top-full mt-2 w-48 bg-white dark:bg-ios-gray-800 rounded-apple-lg shadow-apple-lg border border-ios-gray-200 dark:border-ios-gray-700 z-20">
            <div className="py-2">
              {themes.map((theme) => (
                <button
                  key={theme.id}
                  onClick={() => handleThemeChange(theme.id)}
                  className={`w-full px-4 py-3 text-left hover:bg-ios-gray-50 dark:hover:bg-ios-gray-700 transition-colors ${
                    currentTheme === theme.id ? 'bg-ios-blue/10 text-ios-blue' : 'text-ios-gray-700 dark:text-ios-gray-300'
                  }`}
                >
                  <div className="flex items-center space-x-3">
                    <span className="text-lg">{theme.icon}</span>
                    <div>
                      <div className="font-medium">{theme.label}</div>
                      <div className="text-xs text-ios-gray-500 dark:text-ios-gray-400">
                        {theme.description}
                      </div>
                    </div>
                    {currentTheme === theme.id && (
                      <svg 
                        className="w-4 h-4 ml-auto text-ios-blue" 
                        fill="none" 
                        stroke="currentColor" 
                        viewBox="0 0 24 24"
                      >
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
                      </svg>
                    )}
                  </div>
                </button>
              ))}
            </div>
          </div>
        </>
      )}
    </div>
  );
};

export default ThemeToggle;